import React from 'react';
import { Row, Col, Form, InputNumber, Input, Button, Table, Select, Modal, message } from 'antd';
import { connect } from 'dva';
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams'

const FormItem = Form.Item;
const productAddTempIdPrefix = "productAddTempIdPrefix_";
export default connect(({ orderProduct }) => ({ orderProduct }))((
    Form.create({ wrappedComponentRef: true })(class ChooseProduct extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
                tempSelectProductKeys: [],
                tempSelectProduct: []
            }
        }

        productAddTempId = 0;

        handleCancel = () => {
            this.props.form.setFieldsValue({ productName: "" });
            this.props.form.setFieldsValue({ productModel: ""});
            this.setState({ open: false, tempSelectProductKeys: [], tempSelectProduct: [] })
        }

        handleOpen = () => {
            this.setState({ open: true })
        }

        handleConform = () => {
            //判断所选产品的币种是否与所选币种一致，如果不一致则不允许选择。
            let flag = true;
            let message = "";
            if(this.props.customer && this.props.customer.businessType !="2"){
                R.map((row) => {
                    if (R.isNil(row.zzrate) || R.isNil(row.taxrate)) {
                        flag = false;
                        message = "产品的增值税率或者退税率为空，请维护基础数据!";
                    }
                }, this.state.tempSelectProduct)
            }

            if (flag) {
                let parseList = [];
                R.map((row) => {
                    let parseProduct = {};
                    parseProduct.id = productAddTempIdPrefix + this.productAddTempId; this.productAddTempId++; //临时的唯一id
                    parseProduct.key = parseProduct.id;//加上key 不然会抛错
                    parseProduct.productorderid = this.props.orderId; //订单id
                    parseProduct.productId = row.id; //产品id
                    parseProduct.name = row.name; //品名
                    parseProduct.model = row.model; // 型号
                    parseProduct.branch = row.branch; //品牌
                    parseProduct.branchType = row.branchtype; //品牌类型
                    parseProduct.branchtypename = row.branchtypename; //品牌类型
                    parseProduct.unit = row.unit; //单位
                    parseProduct.price = row.price; //单价
                    parseProduct.originCountry = row.countryOrigin; //原产国
                    parseProduct.productoriginalprice = row.price; //原始单价
                    parseProduct.currency = row.currency; //币种
                    parseProduct.singleWeight = row.weight; //单净重
                    parseProduct.size = row.size; //规格
                    parseProduct.declareElements = row.declarelements; //申报要素
                    parseProduct.hscode = row.hscode; // hscode
                    parseProduct.taxrate = row.taxrate; //退税率
                    parseProduct.zzrate = row.zzrate; //增值税率
                    parseProduct.xfrate = row.xfrate; //消费税率
                    parseProduct.isEffectHscode = row.iseffecthscode; //规格是否影响海关编码
                    parseProduct.drawbackCode = row.drawbackcode; //税局hscode
                    parseProduct.superCondition = row.supercondition;//监管条件
                    parseProduct.originCountryValue = row.countryOriginName; //原产国
                    parseProduct.providerName = row.providerName; //供应商
                    parseProduct.providerId = row.providerId; //供应商id
                    parseList = R.concat(parseList, [parseProduct]);
                }, this.state.tempSelectProduct)

                if (this.props.handleAddProducts) {
                    this.props.handleAddProducts(parseList);
                }
                this.handleCancel();
            } else {
                message.error(message);
                return;
            }
        }

        handleProductSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.orderProduct.page;
            newPage.page = 1;
            this.props.dispatch({
                type: 'orderProduct/queryProductList',
                payload: {
                    ...values,
                    cstId: this.props.cstId,
                    page: newPage
                }
            });
        }


        columns = [
            { title: '海关HSCode', dataIndex: 'hscode', key: 'hscode' },
            { title: '税局HSCode', dataIndex: 'drawbackcode', key: 'drawbackcode' },
            { title: '品名', dataIndex: 'name', key: 'name' },
            { title: '型号', dataIndex: 'model', key: 'model' },
            { title: '品牌类型', dataIndex: 'branchtypename', key: 'branchtypename' },
            { title: '品牌', dataIndex: 'branch', key: 'branch' },
            { title: '单价', dataIndex: 'price', key: 'price' },
            { title: '币种', dataIndex: 'currency', key: 'currency' },
            { title: '申报要素', dataIndex: 'declarelements', key: 'declarelements' },
            { title: '原产地', dataIndex: 'countryOriginName', key: 'countryOriginName'},
            { title: '规格', dataIndex: 'size', key: 'size' },
            { title: '供应商', dataIndex: 'providerName', key: 'providerName'},
            { title: '关税(%)', dataIndex: 'taxrate', key: 'taxrate' },
            { title: '增值税率(%)', dataIndex: 'zzrate', key: 'zzrate' },
            { title: '净重(kg)', dataIndex: 'weight', key: 'weight' }
        ];

        render() {
            let values = this.props.form.getFieldsValue();
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                current: this.props.orderProduct.page.page,
                pageSize: this.props.orderProduct.page.size,
                total: this.props.orderProduct.page.totalRow,
                showSizeChanger: true,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.orderProduct.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'orderProduct/queryProductList',
                        payload: {
                            ...values,
                            cstId: this.props.cstId,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    this.setState({
                        tempSelectMsgKeys: [],
                        tempSelectMsg: []
                    })
                    let newPage = this.props.orderProduct.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'orderProduct/queryProductList',
                        payload: {
                            ...values,
                            cstId: this.props.cstId,
                            page: newPage
                        }
                    });
                }
            }
            const { getFieldDecorator } = this.props.form;

            const formItemLayout = { labelCol: { span: 9 }, wrapperCol: { span: 15 } };

            let rowSelection = {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({
                        tempSelectProductKeys: selectedRowKeys,
                        tempSelectProduct: selectedRows
                    })
                },
                selectedRowKeys: this.state.tempSelectProductKeys
            };

            return (
                <Modal  maskClosable={false} visible={this.state.open} title={"添加产品"} width={1400} wrapClassName="vertical-center-modal" onCancel={this.handleCancel.bind(this)} onOk={this.handleConform.bind(this)}>

                    <Form layout="inline" style={{ marginBottom: 15 }}>

                        <FormItem
                            {...formItemLayout}
                            label="产品名称"
                            hasFeedback
                        >
                            {getFieldDecorator('productName')(
                                <Input maxLength="30" />
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="产品型号"
                            hasFeedback
                        >
                            {getFieldDecorator('productModel')(
                                <Input maxLength="30" />
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="供应商名称"
                            hasFeedback
                        >
                            {getFieldDecorator('suppilerName')(
                                <Input maxLength="30" />
                            )}
                        </FormItem>

                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleProductSearch.bind(this)}>查询</Button>

                    </Form>

                    <Table rowKey={record => record.id} dataSource={this.props.orderProduct.allProducts} rowSelection={rowSelection} columns={this.columns} bordered={false} size={'middle'} pagination={pagination} scroll={{x:1400}}/>

                </Modal>
            );
        }
    })
))